<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Api\v1\Controller;
use App\Http\Resources\GoodsLogisticResource;
use App\Http\Resources\GoodsOrderResource;
use App\Models\Address;
use App\Models\Configuration;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\GoodsEvaluation;
use App\Models\GoodsLogistic;
use App\Models\GoodsOrder;
use App\Models\GoodsOrderAddress;
use App\Models\GoodsOrderDetail;
use App\Models\GoodsSellOrder;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\HttpException;

class GoodsOrderController extends Controller
{
    /**
     * 创建订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|int|min:1',
            'carts' => 'required|array',
            'add_time' => 'date_format:Y-m-d H:i:s'
        ]);
        $data = $request->all();

        //商品处理
        $goods = $this->cart($data['user_id'], $data['carts']);
        //生成订单
        DB::beginTransaction();
        try {
            if(Configuration::getItem('order_create_type') == 'many'){
                foreach ($goods['goods'] as $vg) {
                    $number = $vg->number;
                    $vg->number = 1;
                    for ($i=1; $i <= $number; $i++){
                        $order = GoodsOrder::store($data['user_id'], GoodsOrder::ORDER_CREATE_TYPE_GENERAL, $vg->original_price, $vg->price, $vg->profit, $data['add_time']);
                        $good = $vg;
                        $good->number = 1;
                        GoodsOrderDetail::store($data['user_id'], $order, $vg);
                    }
                }
            }else{
                $order = GoodsOrder::store($data['user_id'], GoodsOrder::ORDER_CREATE_TYPE_GENERAL, $goods['order_total_original_price'], $goods['order_total_price'], $goods['order_total_profit'],$data['add_time']);
                foreach ($goods['goods'] as $vg) {
                    GoodsOrderDetail::store($data['user_id'], $order, $vg);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = in_array($e->getCode(), [300001, 400]) ? $e->getCode() : 40001;
            return $this->fail($code, trans('error.' . $code));
        }
        return $this->success();
    }


    /**
     * 购物车
     * @param $user_id
     * @param $cart_ids
     * @return array|\Illuminate\Http\JsonResponse|object
     */
    public function cart($user_id, $carts)
    {
        //获取购物车数据
        $goods_ids = [];
        $order_total_original_price = $order_total_price = $order_total_profit = 0;
        foreach ($carts as $key => $value) {
            $goods_ids[] = $value['goods_id'];
            $cart_goods[$value['goods_id']] = $value['number'];
        }
        //获取指定商品
        $goods = Goods::getDesignatedGoods($goods_ids);
        if ($goods->isEmpty()) {
            throw new HttpException(Response::HTTP_OK, trans('error.300000'), null, [], 300000);
        }
        foreach ($goods as $val) {
            if ($val->quality < $cart_goods[$val->id]) {
                throw new HttpException(Response::HTTP_OK, trans('error.300001'), null, [], 300001);
            }
            $val->number = $cart_goods[$val->id];
            $val->total_original_price = bcmul($val->original_price, $val->number);
            $val->total_price = bcmul($val->price, $val->number);
            $val->total_profit = bcmul($val->profit, $val->number);

            $order_total_original_price = bcadd($order_total_original_price, $val->total_original_price);
            $order_total_price = bcadd($order_total_price, $val->total_price);
            $order_total_profit = bcadd($order_total_profit, $val->total_profit);

            //减库存
            $val->decrement('quality', $cart_goods[$val->id]);
        }
        $data['goods'] = $goods;
        $data['order_total_original_price'] = $order_total_original_price;
        $data['order_total_price'] = $order_total_price;
        $data['order_total_profit'] = $order_total_profit;
        return $data;
    }

    /**
     * 订单支付
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function payment(Request $request)
    {
        $request->validate([
            'order_ids' => 'required|array',
            'pay_password' => 'required|digits:6'
        ]);
        $order_ids = $request->post('order_ids');
        $user = User::getUser(['tiktokid'=>$request->header('Userid')],0);
        //验证支付密码

        if (empty($request->pay_password)) {
            return $this->fail(10009, trans('error.10009'));
        }
        if (!Hash::check($request->pay_password, $user->payment_password)) {
            return $this->fail(10007, trans('error.10007'));
        }

        DB::beginTransaction();
        try {
            $order = GoodsOrder::query()
                ->whereIn('id', $order_ids)
                ->where('user_id', $user->id)
                ->where('order_status', GoodsOrder::ORDER_UNPAID)
                ->lockForUpdate()
                ->get();
            if ($order->isEmpty()) {
                DB::rollBack();
                return $this->fail(40039, trans('error.40039'));
            }
            //修改订单状态
            GoodsOrder::payment($order, $user);
            DB::commit();
            //$user->save();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('商品订单支付失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'page' => $e->getLine()]);
            $code = $e->getCode() == 10016 ? 10016 : 40039;
            return $this->fail($code, trans('error.' . $code));
        }
        return $this->success();
    }

    /**
     * 取消订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function cancel(Request $request)
    {
        $request->validate([
            'order_id' => 'required|int',
        ]);
        $user = $request->user();
        DB::beginTransaction();
        try {
            GoodsOrder::cancel($user->id, $request->order_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            //Log::info('订单取消失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'page' => $e->getLine()]);
            return $this->fail(40018, trans('error.40018'));
        }
        return $this->success();
    }

    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function orderList(Request $request)
    {
        $request->validate([
            'type' => 'required|string',
            'page' => 'required|int',
            'limit' => 'required|int'
        ]);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 100);
        $page = $this->paging($page, $limit);
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $order = null;
        $order_field = $request->get('order_field', 'order_total_original_price');
        $order_turn = $request->get('order_turn', 'DESC');
        switch ($request->type) {
            case 'all':
                $order = GoodsOrder::getList($user->id, [], [], $page, $limit,$order_field,$order_turn);
                break;
            case 'pending': //待支付
                $where = [
                    'order_status' => GoodsOrder::ORDER_UNPAID
                ];
                $order = GoodsOrder::getList($user->id, $where, [], $page, $limit,$order_field,$order_turn);
                break;
            case 'pending-d': //待发货
                $where = [
                    'order_status' => GoodsOrder::ORDER_PAID
                ];
                $order = GoodsOrder::getList($user->id, $where, [], $page, $limit,$order_field,$order_turn);
                break;
            case 'unreceived': //待收货
                $where = [
                    'order_status' => GoodsOrder::ORDER_NOT_RECEIVED
                ];
                $order = GoodsOrder::getList($user->id, $where, [], $page, $limit,$order_field,$order_turn);
                break;
            case 'cancel': //取消
                $where = [];
                $whereIn = ['order_status', [GoodsOrder::ORDER_CANCEL, GoodsOrder::ORDER_TIME_OUT_CANCEL]];
                $order = GoodsOrder::getList($user->id, $where, $whereIn, $page, $limit,$order_field,$order_turn);
                break;
            case 'completed': //完结
                $where = [];
                $whereIn = ['order_status', [GoodsOrder::ORDER_REFUNDED, GoodsOrder::ORDER_END]];
                $order = GoodsOrder::getList($user->id, $where, $whereIn, $page, $limit,$order_field,$order_turn);
                break;

            default:

                break;
        }
        return $this->success(GoodsOrderResource::collection($order));
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|object
     */
    public function orderDetail(Request $request)
    {
        $request->validate([
            'order_id' => 'required|int',
        ]);
        $user = $request->user();
        $order = GoodsOrder::detail($user->id, $request->order_id, false);
        if (empty($order)) {
            return $this->fail(404, trans('error.404'));
        }
        //收货地址
        $select = ['pin_code', 'name', 'phone', 'address_detail', 'landmark', 'area', 'city', 'state'];
        $address = GoodsOrderAddress::getAddress($order->id, $select);
        $order->address = $address;
        //获取物流信息
        $logistics = null;
        if ($order->order_status == GoodsOrder::ORDER_NOT_RECEIVED) {
            $logistics = GoodsLogisticResource::collection(GoodsLogistic::getListByGoodId($order->id));
        }
        $order->logistics = $logistics;
        return $this->success(GoodsOrderResource::make($order));
    }



}
